using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;

/// <summary>
/// Summary description for ChatEngine
/// </summary>

public class ChatEngine
{
    static ChatEngine() { }

    public static bool SendMessage(string message, GridPool upool, User user) //return false if failed
    {
        try
        {
            DateTime time = DateTime.Now;
            //add a message to associated grid
            user.LocationInPool.lati.Messages.Add(time, new Message(message,user.UserName, time));
        }
        catch (NullReferenceException e) { throw new NoClientUserInformationException(); }
        user.LastCommunicated = DateTime.Now;
        return true;
    }

    public static string GetMessages(GridPool upool, User user, DateTime since)
    {
        List<AreaGrid> grids = upool.GetGrids(user.Location, user.Range);
        SortedList<DateTime, Message> messages = new SortedList<DateTime, Message>();
        foreach (AreaGrid grid in grids)
            foreach (KeyValuePair<DateTime,Message> msg in grid.Messages)
                if (msg.Value.Time.CompareTo(since) <= 0)
                    messages.Add(msg.Value.Time,msg.Value);
        
        StringBuilder sb = new StringBuilder();
        foreach (KeyValuePair<DateTime,Message> msg in messages)
        {
            sb.Append(@"<div class=""MessagePanel"">");
            sb.Append(@"<span class=""MessageTime"">" 
                + msg.Value.Time.ToShortDateString() + " " 
                + msg.Value.Time.ToShortTimeString() + @"</span>&nbsp;") ;
            sb.Append(@"<span class=""MessageSender"">" + msg.Value.Sender + @": </span>&nbsp;");
            sb.Append(@"<span class=""MessageBody"">" + msg.Value.Body + @"</span>&nbsp;");
            sb.Append(@"</div>");
        }
        user.LastCommunicated = 
            //user.LastReceiveTime =
            DateTime.Now;
        return sb.ToString();

    }


    public class NoClientUserInformationException:Exception{}
    }